import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/card_info_entity.dart';
import 'package:nyh_motorcade_app/entity/energy_type_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CardManageController extends GetxController {
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  ScrollController scrollController = ScrollController();

  //来自于卡管理(或者卡账户)
  bool isFormCardManage = false;
  int cardCount = 0;
  String energyType = "";
  String energyTypeName = "";
  String cardType = "";
  String cardTypeName = "";
  int page = 1;
  List<EnergyTypeEntity> energyTypeList = [];
  List<CardType> cardTypeList = [];
  bool showEnergyTypeMenu = false;
  bool showCardTypeMenu = false;
  List<CardInfoItem> cardInfoList = [];
  bool permissionTransferCard = false;

  @override
  Future<void> onReady() async {
    super.onReady();
    isFormCardManage = Get.arguments ?? false;
    update();
    permissionTransferCard = await SPUtils.getBool(SPUtils.PERMISSION_TRANSFER_CARD);
    initCardTypeList();
    getCardInfoList();
  }

  Future<void> onRefresh() async {
    page = 1;
    getCardInfoList();
  }

  Future<void> onLoading() async {
    getCardInfoList();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getCardInfoList();
  }

  Future<void> goToActivateCardPage() async {
    dynamic data = await Get.toNamed(Routes.addCard, arguments: {Constant.PARAM_IS_RETURN: true});
    if (data != null) {
      page = 1;
      multiState = MultiState.loading;
      update();
      getCardInfoList();
    }
  }

  void goToCardDetailsOrCardCashFlowPage(String? id) {
    if (isFormCardManage) {
      Get.toNamed(Routes.cardDetails, arguments: id);
    } else {
      Get.toNamed(
        Routes.cashFlow,
        arguments: {
          "sourceId": id,
          "accountType": Constant.CARD,
        },
      );
    }
  }

  Future<void> goToRapidTransferPage(String? id, String? name, double? amount) async {
    dynamic data = await Get.toNamed(Routes.rapidTransfer, arguments: {
      Constant.PARAM_RAPID_TRANSFER_FROM: Constant.RAPID_TRANSFER_FROM_CARD,
      Constant.PARAM_ACCOUNT_ID: id,
      Constant.PARAM_ACCOUNT_NAME: name ?? "",
      Constant.PARAM_ACCOUNT_AMOUNT: amount ?? 0.0,
    });
    if (data != null) {
      page = 1;
      multiState = MultiState.loading;
      update();
      getCardInfoList();
    }
  }

  Future<void> getCardInfoList() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_CARD_INFO_LIST,
      {
        "superId": await SPUtils.getString(SPUtils.COMPANY_ID),
        "energyType": energyType,
        "cardType": cardType,
      },
      headers: {"page": page, "limit": 10},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          } else {
            refreshController.loadFailed();
          }
          if (page == 1) {
            multiState = MultiState.fail;
          }
          update();
          return;
        }
        CardInfoEntity cardInfoEntity = CardInfoEntity().fromJson(data);
        cardCount = cardInfoEntity.total ?? 0;
        List<CardInfoItem> list = cardInfoEntity.item ?? [];
        if (list.isNotEmpty) {
          multiState = MultiState.success;
          if (refreshController.isRefresh) {
            cardInfoList.clear();
            refreshController.refreshCompleted();
            if (scrollController.hasClients) {
              scrollController.jumpTo(0);
            }
          } else {
            if (list.length >= 10 || page == 1) {
              refreshController.loadComplete();
            } else {
              refreshController.loadNoData();
            }
          }
          if (page == 1) {
            cardInfoList.clear();
          }
          cardInfoList.addAll(list);
          page++;
        } else {
          if (refreshController.isRefresh) {
            refreshController.refreshCompleted();
          } else {
            refreshController.loadNoData();
          }
          if (page == 1) {
            multiState = MultiState.empty;
          }
        }
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.fail;
        }
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.error;
        }
        update();
      },
    );
  }

  Future<List<EnergyTypeEntity>> getEnergyType() async {
    if (energyTypeList.isNotEmpty) {
      return energyTypeList;
    }
    HttpResult httpResult = await httpManager.post(Get.context, HttpAddress.GET_ENERGY_TYPE, {}, isToast: true, isLoadingDialog: true);
    dynamic data = httpResult.data;
    if (data == null) {
      return [];
    }
    if (data is List) {
      energyTypeList = data.map((element) {
        return EnergyTypeEntity().fromJson((element as Map<String, dynamic>));
      }).toList();
      EnergyTypeEntity energyTypeEntity = EnergyTypeEntity();
      energyTypeEntity.dictdataName = "全部";
      energyTypeEntity.dictdataValue = "";
      energyTypeList.insert(0, energyTypeEntity);
      return energyTypeList;
    }
    return [];
  }

  void setSelectEnergyType(int? value) {
    showEnergyTypeMenu = false;
    if (value != null) {
      String type = energyTypeList[value].dictdataValue ?? "";
      energyTypeName = value != 0 ? (energyTypeList[value].dictdataName ?? "") : "全部类型";
      if (energyType != type) {
        energyType = type;
        page = 1;
        multiState = MultiState.loading;
        getCardInfoList();
      }
    }
    update();
  }

  void setSelectCardType(int? value) {
    showCardTypeMenu = false;
    if (value != null) {
      String type = cardTypeList[value].type;
      cardTypeName = value != 0 ? cardTypeList[value].name : "全部归属";
      if (cardType != type) {
        cardType = type;
        page = 1;
        multiState = MultiState.loading;
        getCardInfoList();
      }
    }
    update();
  }

  void initCardTypeList() {
    cardTypeList.add(CardType("全部", ""));
    cardTypeList.add(CardType("自有", Constant.OWN_CARD));
    cardTypeList.add(CardType("外协", Constant.EXTERNAL_CARD));
  }
}

class CardType {
  String name;
  String type;

  CardType(this.name, this.type);
}
